# -*- coding: utf-8 -*-
# article_search.py
# Created by Hardy on 2017/08/14
# Copyright 2017 杭州网川教育有限公司. All rights reserved.

import datetime

import numpy

import utils.utils as utils
from querier.esquerier import ElasticSearchQuerier

MAX_KEYWORDS = 50


class HotWordTrendQuerier(ElasticSearchQuerier):
    def __init__(self, wechat_pub_stat_multi_query, nlp_service):
        super(HotWordTrendQuerier, self).__init__(None, None, None)
        self.nlp_service = nlp_service
        self.wechat_pub_stat_multi_query = wechat_pub_stat_multi_query

    def search(self, args):
        word = args.get('word', '')
        word = word.strip() if word else ''

        filters = args.get('filters', {})
        filters = filters if filters else {}

        date = datetime.datetime.now()
        default_end_time = date.strftime('%Y-%m-%d %H:%M:%S')
        from_date = args.get('from_date')
        to_date = args.get('to_date')
        if from_date is None:
            from_date = '2017-10-01 00:00:00'
        if to_date is None:
            to_date = default_end_time

        # 处理查询文本
        keyword_type = 'keywordcloud'
        # 处理查询文本
        term2, keywords, ex_keywords, weights = utils.process_query_term(word, self.nlp_service, keyword_type,
                                                                         allowed_num_words=MAX_KEYWORDS)

        a = {"keywords": ex_keywords[0:5], 'from_date': from_date, 'to_date': to_date, "filters": filters}
        stat_data = self.wechat_pub_stat_multi_query.search(a)["pub_stat"]
        res = []
        date_list = []
        for data in stat_data:
            dates = data.get('dates')
            date_list.append(dates)
            df = data.get('df')
            source = data.get('from')
            word = data.get('word')
            kv = {"word": word, "source": source, "df": df, "dates": dates}
            res.append(kv)

        new_res = []
        res_date = sorted(list(set([x for sub_list in date_list for x in sub_list ])))
        for kv_data in res:
            date_df_dict = dict(zip(kv_data.get("dates"), kv_data.get("df")))
            new_df = [date_df_dict.get(x, 0) for x in res_date]
            word = kv_data.get('word')
            new_kv = {"word": word, "df": new_df}
            new_res.append(new_kv)

        return {"data": new_res, "date": res_date}

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass
